package com.mastercard.labs

import grails.converters.JSON
import java.text.SimpleDateFormat
import org.springframework.dao.DataIntegrityViolationException
import org.apache.shiro.SecurityUtils

class DealController {

//    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def cardService, transactionService, categoryService, transactionCategoryService, dealService, userService, merchantService, voucherService
	
    def index() {
        redirect(action: "list", params: params)
    }

/*    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [dealInstanceList: Deal.list(params), dealInstanceTotal: Deal.count()]
    }
*/	
	def list() {
		log.info "DealConroller list()"
		if(params.prevAction == "dashboard"){
			redirect(controller: "dashboard")
		}else if(params.search == "Search"){
			log.info "DealConroller search()"
			def dealInstanceList = dealService.searchByCondition(params.searchTitle, params.searchCountry, params.searchMerchant, params.searchCategories);
			
			[dealInstanceList: dealInstanceList,
			searchTitle: params.searchTitle,
			searchMerchant: params.searchMerchant,
			searchCategories: params.searchCategories,
			searchCountry: params.searchCountry
			]
		}
	}

    def create() {
		log.info "DealConroller create()"
		def formatter = new SimpleDateFormat("dd-MM-yyyy")
		
        [dealInstance: new Deal(params),
		dateFormat: formatter]
    }

    def save() {
		log.info "DealConroller save()"
        def dealInstance = new Deal(params)
		
		/*if (dealInstance.getStartDate().before(new Date() -1) ) {
			flash.error = message(code: 'deal.invalid.startDate.message')
			flash.message = null
			render(view: "create", model: [dealInstance: dealInstance])
			return
		}*/
		
        if (!dealInstance.save(flush: true)) {
            render(view: "create", model: [dealInstance: dealInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'deal.label', default: 'Deal'), dealInstance.title])
        redirect(action: "create", id: dealInstance.id)
    }

    def show() {
		log.info "DealConroller show()"
        def dealInstance = Deal.get(params.id)
        if (!dealInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])
            redirect(action: "list")
            return
        }

        [dealInstance: dealInstance]
    }

    def edit() {
		log.info "DealConroller edit()"
        def dealInstance = Deal.get(params.id)
        if (!dealInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])
            redirect(action: "list")
            return
        }

        [dealInstance: dealInstance, prevAction: params.prevAction]
    }
	
	def validateStartDate(obj) {
		Date oriDate = obj.getStartDate()
		log.info 'db start date:' + oriDate
		log.info 'input start date:' + params.startDate_value
		log.info 'input db start date:' + params.dbStartDate
		if (params.startDate_value == null || '' == params.startDate_value) return true
		return Date.parse("MM/dd/yyyy", params.startDate_value).after(oriDate -1)
	}

    def update() {
		log.info "DealConroller update()"
        def dealInstance = Deal.get(params.id)
        if (!dealInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])
            redirect(action: "list")
            return
        }
		
		if (!validateStartDate(dealInstance)){
            //flash.message = message(code: 'default.not.found.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])
			//dealInstance.errors.addError("startDate", "something bad happened")
			
			dealInstance.errors.rejectValue(
				'startDate',
				'user.startDate.doesnotmatch',
				'start Date should be not before than [' + dealInstance.getStartDate().format("MM/dd/yyyy") + ']')
			
            render(view: "edit", model: [dealInstance: dealInstance])
            return
        }
		
		if (params.version) {
            def version = params.version.toLong()
            if (dealInstance.version > version) {
                dealInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'deal.label', default: 'Deal')] as Object[],
                          "Another user has updated this Deal while you were editing")
                render(view: "edit", model: [dealInstance: dealInstance])
                return
            }
        }

		if(!params."merchant.id" || params."merchant.id" == "") {
			params.merchant == null
			params.remove("merchant.id")
			dealInstance.setMerchant(null)
		}
		
	/*	if(!params."categories" || params."merchant.id" == "") {
			params.merchant == null
			params.remove("merchant.id")
			dealInstance.setMerchant(null)
		}*/
		
        dealInstance.properties = params

        if (!dealInstance.save(flush: true)) {
            render(view: "edit", model: [dealInstance: dealInstance])
            return
        }
		
		flash.message = message(code: 'default.updated.message', args: [message(code: 'deal.label', default: 'Deal'), dealInstance.title])
        redirect(action: "edit", id: dealInstance.id)
    }

    def delete() {
		log.info "DealConroller delete()"
        def dealInstance = Deal.get(params.id)
        if (!dealInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'deal.label', default: 'Deal'), params.id])
            redirect(action: "list")
            return
        }

        try {
            dealInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'deal.label', default: 'Deal'), params.title])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'deal.label', default: 'Deal'), params.title])
            redirect(action: "show", id: params.id)
        }
    }
	
	def searchDeals() {
		def searchTitle = params.query
		def categoryIds = params.category_id
		def user = SecurityUtils.subject.session.getAttribute("current_user")
		
		def searchedDeals
		if (searchTitle) {
			searchedDeals = dealService.searchDeals(searchTitle)
		}
		else if (categoryIds)  {
			if (categoryIds instanceof String) {
				categoryIds = [categoryIds]
			}
			println categoryIds
			searchedDeals = dealService.searchDealsInCategorires(categoryIds)
		}
		
		def categoryIdSets;
		if (categoryIds) {
			categoryIdSets = Arrays.asList(categoryIds)
		} else {
			categoryIdSets = Arrays.asList([])
		}
		
		def categories = categoryService.getAll()
		println searchTitle
		render (view: "search_deal", model:[
			searchedDeals: searchedDeals,
			deals: dealService.getDeals(user),
			categories: categories,
			searchedCategories:categoryIdSets])
	}
	
	def testFavoriteMerchant() {
		def user = User.findByEmail("zhongde@gmail.com")
		render text: new JSON(dealService.getFavoriteMerchants(user))
	}
	
	def testAverageSpending() {
		def user = User.findByEmail("guoyu@gmail.com")
		render text: dealService.getAverageSpending(user)
	}
	
	def testDeals() {
		def user = User.findByEmail("zhongde@gmail.com")
		render text: new JSON(dealService.getDeals(user))
	}
}
